//
//  BiZhiViewController.m
//  Hero
//
//  Created by lanou3g on 16/5/6.
//  Copyright © 2016年 刘永庆. All rights reserved.
//

#import "BiZhiViewController.h"
#import "PicModel.h"
#import "CustomLayout.h"
@interface BiZhiViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,CustomLayoutDelegate>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UICollectionView *conllectionView;
@end

@implementation BiZhiViewController
static NSInteger count = 0;
- (void)dealloc
{
    [self.conllectionView removeObserver:[self.conllectionView defaultFooter]  forKeyPath:@"contentSize"];
    [self.conllectionView removeObserver:[self.conllectionView defaultFooter]  forKeyPath:@"contentOffset"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"壁纸";
    self.dataArray = [[NSMutableArray alloc]init];
    [self reloadDate];
    CustomLayout *layout = [[CustomLayout alloc]init];
    layout.delegate = self;
    //设置布局的宽度
    CGFloat width = ([[UIScreen mainScreen]bounds].size.width - 40) / 2;
    //设置item的大小
    layout.itemSize = CGSizeMake(width, width);
    layout.insertItemSpacing = 10;
    layout.numberOfColumns = 2;
//    layout.itemSize = CGSizeMake(180, 220);
    layout.sectionInsets = UIEdgeInsetsMake(20, 20, 20, 20);
    UICollectionView *colletionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
    [self.view addSubview:colletionView];
    self.conllectionView = colletionView;
    self.conllectionView.backgroundColor = [UIColor whiteColor];
    self.conllectionView.delegate = self;
    self.conllectionView.dataSource = self;
    [self.conllectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"picCell"];
    __weak typeof(self)weakSelf = self;
    [self.conllectionView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        [weakSelf reloadDate];
    }];
}
- (void)reloadDate
{
    [YQNetWorkRequestManager requestURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://qt.qq.com/php_cgi/lol_goods/varcache_wallpaper_list.php?type=new&page=%ld&num=20&plat=android&version=9695",count++]] method:YQ_GET params:nil result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            for (NSDictionary *dic in dict[@"wallpapers"]) {
                PicModel *model = [PicModel new];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.conllectionView reloadData];
                [[self.conllectionView defaultFooter]endRefreshing];
            });
        }
    }];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"picCell" forIndexPath:indexPath];
    UIImageView *view = [[UIImageView alloc]initWithFrame:cell.bounds];
    PicModel *model = self.dataArray[indexPath.row];
    
    [view sd_setImageWithURL:[NSURL URLWithString:model.thumbUrl]];
    cell.backgroundView = view;
    return cell;
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicModel *model = self.dataArray[indexPath.row];
    
    [UIView animateWithDuration:2 animations:^{
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectZero];
        imageView.tag = 3000;
        imageView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.url]];
        
        [self.view addSubview:imageView];
        UIBarButtonItem *bar = [[UIBarButtonItem alloc]initWithTitle:@"操作" style:UIBarButtonItemStyleDone target:self action:@selector(alertAction:)];
        self.navigationItem.rightBarButtonItem = bar;
        self.conllectionView.userInteractionEnabled = NO;
    }];
   
}
- (void)alertAction:(NSString *)url
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择进行的操作" preferredStyle:UIAlertControllerStyleActionSheet];
//    [alert addAction:[UIAlertAction actionWithTitle:@"收藏" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImageView *view = [self.view viewWithTag:3000];
        UIImageWriteToSavedPhotosAlbum(view.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [UIView animateWithDuration:3 animations:^{
            UIImageView *view = [self.view viewWithTag:3000];
            view.frame = CGRectMake(self.view.frame.size.width, self.view.frame.size.height, 0, 0);
            view.tag = 3001;
            UIBarButtonItem *item = [[UIBarButtonItem alloc]init];
            self.navigationItem.rightBarButtonItem = item;
        }];
        self.conllectionView.userInteractionEnabled = YES;
//        UIBarButtonItem *bar = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(cancleAction)];
//        self.navigationItem.rightBarButtonItem = bar;
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    if (!error) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"成功保存到相册" preferredStyle:UIAlertControllerStyleActionSheet];
       [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:Nil]];
        [self presentViewController:alert animated:YES completion:^{
            [UIView animateWithDuration:3 animations:^{
                UIImageView *view = [self.view viewWithTag:3000];
                view.frame = CGRectMake(self.view.frame.size.width, self.view.frame.size.height, 0, 0);
                UIBarButtonItem *item = [[UIBarButtonItem alloc]init];
                self.navigationItem.rightBarButtonItem = item;
                view.tag = 3003;
            }];
            self.conllectionView.userInteractionEnabled = YES;

        }];
    }else
    {
       
    }
    
}
- (CGFloat)heightItemForIndextPath:(NSIndexPath *)indexPath
{
    //获取model的对象
    PicModel *model = self.dataArray[indexPath.row];
    CGFloat width = [UIScreen mainScreen].bounds.size.width - 40 / 2;
    CGFloat height = ([model.thumb_height floatValue] / 2 / [ model.thumb_width floatValue]) *width;
    return height;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
